#include "biz.h"
#include "lib/json.hpp"
#include "X7.h"
using json = nlohmann::json;
#include "core/reactor/peerConnection.h"

biz* biz::instance = nullptr;
std::mutex biz::lock;
forwardList biz::list; 

//用户数据的业务处理流程
void biz::userReqHandler(std::map<string,string> dataSet, connection_t* conn)
{
    
    json res;
    //协议解析完成后，执行后续步骤
    string tempData = dataSet["data"];
    try{
        auto userData = json::parse(tempData);
        if(userData.find("user_id") == userData.end() || userData.find("user_code") == userData.end()){
            res["status"] = 401;
            res["msg"] = "用户信息不正确";
            string data = res.dump();
            echo(data, conn, utils);
            return;
        }
        if(utils.peers.peers.size() == 0){
            res["status"] = 402;
            res["msg"] = "解释器端连接失败";
            string data = res.dump();
            echo(data, conn, utils);
            return;
        }
        //负载均衡
        connection_t* temp = utils.peers.getConnection();
        if(temp == nullptr){
            res["status"] = 301;
            res["msg"] = "获取解释器端连接失败，请检查负载均衡模块";
            string data = res.dump();
            echo(data, conn, utils);
            return;
        }
        string forwardId = list.getForwardId(conn);
        if(forwardId.empty()){
            forwardId = list.insertUser(conn);
        }
        if(forwardId.empty()){
            res["status"] = 300;
            res["msg"] = "获取forward_id出错，请联系管理员";
            string data = res.dump();
            echo(data, conn, utils);
            return;
        }
        userData["forward_id"] = forwardId;
        string tempData = userData.dump();
        string data = X7::encoder(tempData);
        echo(data, temp, utils);
        //std::cout << "转发数据为" << data <<std::endl;

    }catch(nlohmann::detail::parse_error)
    {
        //json解析错误，向用户返回错误信息
        res["status"] = 403;
        res["msg"] = "用户信息解析错误";
        string data = res.dump();
        echo(data, conn, utils);
        return;
    }

}


biz* biz::getInstance(cycle_t& utils)
{
    {
        if(instance == nullptr){
            std::lock_guard<std::mutex> temp(lock);
            if(instance == nullptr){
                static biz haha(utils);
                instance = &haha;
            }
        }
        return instance;
    }
}

//对端服务器（Runner）的业务处理流程
void biz::peerReqHandler(string tempData, connection_t* conn)
{
    auto logger = utils.logger.setBasicLogger("biz");
    json res;
    try{
        auto peerData = json::parse(tempData);
        if(peerData.find("forward_id") == peerData.end()){
           logger->error("解释器端发送的数据缺失forward_id");
           return;
        }
        string forwardId = peerData["forward_id"].get<string>();
        connection_t* temp = list.getUserConn(forwardId);
        if(temp == nullptr){
            logger->error("解释器端发来了无效的forward_id");
            return; 
        }
        res["msg"] = peerData["msg"];
        res["status"] = peerData["status"];
        string data = res.dump();
        echo(data, temp, utils);
    }catch(nlohmann::detail::parse_error)
    {
        //json解析错误，向用户返回错误信息
        res["status"] = 403;
        res["msg"] = "用户信息解析错误";
        string data = res.dump();
        echo(data, conn, utils);
        return;
    }
}